package org.mclll.xwangplugin.oraxenFix;

import io.th0rgal.oraxen.api.events.furniture.OraxenFurnitureBreakEvent;
import io.th0rgal.oraxen.api.events.furniture.OraxenFurniturePlaceEvent;
import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;

public class FurniturePlaceListener implements Listener {


    // 家具无视领地放置
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onFurniturePlace(OraxenFurniturePlaceEvent event) {
        Player player = event.getPlayer();
        Block block = event.getBlock();
        BlockPlaceEvent event1 = new BlockPlaceEvent(block, block.getState(), block, player.getInventory().getItemInMainHand(), player, false, player.getHandRaised());
        Bukkit.getPluginManager().callEvent(
                event1
        );
        event.setCancelled(event1.isCancelled());
    }

    // 实体家具无视领地拆除
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onFurnitureBreak(OraxenFurnitureBreakEvent event) {
        Player player = event.getPlayer();
        Block block = event.getBlock();
        if (block.getType() == Material.BARRIER) {
            return;
        }
        BlockBreakEvent event1 = new BlockBreakEvent(block, player);
        Bukkit.getPluginManager().callEvent(
                event1
        );
        event.setCancelled(event1.isCancelled());
    }

    // 灯具光源清除
    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onFurniturePlace(OraxenFurnitureBreakEvent event) {
        FurnitureMechanic mechanic = event.getMechanic();
        if (mechanic.hasDisplayEntityProperties() && mechanic.getDisplayEntityProperties().hasBrightness()) {
            event.getBlock().setType(Material.AIR);
        }
    }

    // note_block连续放置fix
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onFurniturePlace(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        Block clickedBlock = event.getClickedBlock();
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK && clickedBlock != null && clickedBlock.getType() == Material.NOTE_BLOCK) {
            ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
            if (itemInMainHand.getType() != Material.AIR && itemInMainHand.getItemMeta().hasCustomModelData()) {
                event.setCancelled(true);
            }
        }
    }

}
